package com.qudian.pay.log.autoproxy;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

/**
 * @Description:基于Package和BeanName筛选Bean的自动代理创建者
 * @ClassName: PackageBeanNameAutoProxyCreator
 * @author zhangyabo
 * @date 2017年10月25日 下午3:01:33
 */
public class PackageBeanNameAutoProxyCreator extends BeanNameAutoProxyCreator {

    private static final long serialVersionUID = -8681885630512576826L;

    private String[] basePackages;

    private static final String CONFIG_LOCATION_DELIMITERS = ",; \t\n";

    public void setBasePackage(String basePackage) {
        basePackages = StringUtils.tokenizeToStringArray(basePackage, CONFIG_LOCATION_DELIMITERS);
    }

    @Override
    protected boolean isMatch(String beanName, String mappedName) {
        boolean isMatch = PatternMatchUtils.simpleMatch(mappedName, beanName);

        if (!isMatch) {
            return isMatch;
        }

        if (basePackages == null || basePackages.length < 1) {
            return isMatch;
        }

        BeanFactory beanFactory = getBeanFactory();
        for (String basePackage : basePackages) {
            if (beanName.startsWith(basePackage)) {
                return true;
            }

            Class<?> clazz;
            try {
                clazz = beanFactory.getType(beanName);
            } catch (NoSuchBeanDefinitionException e) {
                // ignore
                return false;
            }

            if (clazz.getName().startsWith(basePackage)) {
                return true;
            }
        }
        return false;
    }
}